package com.code2roc.fastboot.framework.security;

import com.code2roc.fastboot.framework.util.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class XSSFilter implements Filter, Ordered {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String contentType = request.getContentType();
        SecurityConfig securityConfig = BeanUtil.getBean(SecurityConfig.class);
        if (StringUtils.isNotBlank(contentType) && contentType.contains("application/json") && securityConfig.isOpenXSS()) {
            XSSBodyRequestWrapper xssBodyRequestWrapper = new XSSBodyRequestWrapper((HttpServletRequest) request);
            chain.doFilter(xssBodyRequestWrapper, response);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public int getOrder() {
        return 9;
    }
}
